package service;

import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.User;
import utils.SqlSessionFactoryUtils;

public class UserService {
    //使用工具类获取SqlSessionFactory
    static SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    /*** 登录方法 */
    public User login(String username, String password){
        //1. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //3. 调用方法
        User user = mapper.selectByUsername(username);
        //4. 释放资源
        sqlSession.close();
        //5. 验证密码
        if(user != null){
            //继续对比
            if(password.equals(user.getPassword())){
                //验证通过
                return user;
            }else{
                 //密码不符
                return null;
            }
        }
        //因为用户不存在导致失败
        return null;
    }



    //注册用户
    public Object register(String username, String password) {
        //1. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2. 获取UserMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //先检查此用户名是否可以被注册
        User user = userMapper.selectByUsername(username);
        sqlSession.close();
//        if(user !=null){
//            //如果此条件成立，代表数据库中已有该名称的用户
//            return false;
//        }
//        //        如果能被注册，则执行注册操作
//       User newUser = new User(null, username, password);
//        int i= UserMapper.add(newUser);//添加成功的用户量
//       return i>0;
//    }

        if(user != null){
            if(!user.getPassword().equals(password)){
                //密码不符
                return null;
            }else{
                //验证通过
                return user;
            }
        }
        return null;
            }


    //检查用户名是否存在
//    @return true 存在；false 不存在
    public static boolean checkUsername(String username) {
        //1. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2. 获取UserMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //先检查此用户名是否可以被注册
        User user = userMapper.selectByUsername(username);
        if(user !=null){
            //如果此条件成立，代表数据库中已有该名称的用户
            return true;
        }
        sqlSession.close();
        return false;
    }
}
